package com.meila.cms.services.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.meila.cms.dao.CarDesignMapper;
import com.meila.cms.dao.CarInstructionsDesignMapper;
import com.meila.cms.entity.AjaxObj;
import com.meila.cms.entity.CarInstructionsDesign;
import com.meila.cms.model.CarDesignModel;
import com.meila.cms.model.CarInstructionsDesignModel;
import com.meila.cms.model.SQLAdapterModel;
import com.meila.cms.services.ICarInstructionsService;
import com.meila.cms.util.DictUtil;
import com.meila.cms.util.HtmlUtil;
import com.meila.cms.util.ResourceLoader;
import com.meila.cms.util.freemark.HtmlGenerator;
import com.meila.cms.util.json.JsonUtil4;
import com.meila.cms.util.pdf.PdfDocumentGenerator;
 

@Service
public class CarInstructionService extends BaseService implements ICarInstructionsService{

	private final static HtmlGenerator htmlGenerator;
	static {
		htmlGenerator = new HtmlGenerator();
	}
 

	public static HtmlGenerator getHtmlgenerator() {
		return htmlGenerator;
	}

 
	@Override
	public CarInstructionsDesignModel craftOrderList(CarInstructionsDesign carInstructionsDesign) {
		// TODO Auto-generated method stub
		
		CarDesignModel carDesignModel=carDesignMapper.selectByPrimaryKey(carInstructionsDesign.getDesignid());
		
	 
		CarInstructionsDesignModel carInstructionsDesignModel = new CarInstructionsDesignModel();
		carInstructionsDesignModel.setDesignid(carInstructionsDesign.getDesignid());
 
		carInstructionsDesignModel.setCartype(dictUtil.getNameByValue("CarType", carDesignModel.getCartype().toString()));
		carInstructionsDesignModel.setAlias(carDesignModel.getAlias());
		
		List<CarInstructionsDesign> list = carInstructionsDesignMapper.findCarInstructions(carInstructionsDesign);
		carInstructionsDesignModel.setValueList(list);
		 
		return carInstructionsDesignModel;
	}

	@Override
	public Boolean addCarInstructions(CarInstructionsDesignModel carInstructionsDesignModel) {
		// TODO Auto-generated method stub
		try {
			//把所有超过目标指令号的指令号加1
			SQLAdapterModel sql=new SQLAdapterModel();
			sql.setSql(" update t_car_instructions_design" +
					   " set instructionsno=instructionsno+1 " +
					   " where del=0 and instructionsno >="+carInstructionsDesignModel.getInstructionsno()+
					   " and designId="+carInstructionsDesignModel.getDesignid());
			
			dictMapper.updateBySQL(sql);
			 
			carInstructionsDesignMapper.insertSelective(carInstructionsDesignModel);
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
			// TODO: handle exception
		}
		
		return true;
	}

	@Override
	public AjaxObj delCarInstructions(String ids,String designid) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		String id[]=ids.split(",");
		try {
			CarInstructionsDesign carInstructionsDesign;
			for (int i = 0; i < id.length; i++) {
				
				//把所有超过目标指令号的指令号减1
				carInstructionsDesign = carInstructionsDesignMapper.selectByPrimaryKey(Integer.valueOf(id[i]));
				
				SQLAdapterModel sql=new SQLAdapterModel();
				sql.setSql(" update t_car_instructions_design " +
						   " set instructionsno=instructionsno-1" +
						   " where del=0 and instructionsno >"+carInstructionsDesign.getInstructionsno()+"" +
						   " and designId="+designid);
				
				dictMapper.updateBySQL(sql); 
				
				carInstructionsDesign = new CarInstructionsDesign();
				carInstructionsDesign.setId(Integer.valueOf(id[i]));
				carInstructionsDesign.setUpdatetime(new Date());
				carInstructionsDesign.setDel(1);
				carInstructionsDesignMapper.updateByPrimaryKeySelective(carInstructionsDesign);

			}

			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("删除失败");
		}

		ajaxObj.setMsg("删除成功");
		return ajaxObj;
	}

	@Override
	public AjaxObj saveEditInstructions(List<JSONObject> instructionListModels) {
		// TODO Auto-generated method stub
		
		AjaxObj ajaxObj=new AjaxObj();
		try {
			for (JSONObject jSONObject : instructionListModels) {
			 
				CarInstructionsDesign carInstructionsDesign=(CarInstructionsDesign) JsonUtil4.getInstance().json2obj(jSONObject.toJSONString(),CarInstructionsDesign.class);
				carInstructionsDesignMapper.updateByPrimaryKeySelective(carInstructionsDesign);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("保存失败");
			return ajaxObj;
		}

		ajaxObj.setMsg("保存成功");
		return ajaxObj;
	}

	@Override
	public ResponseEntity<byte[]> exportPDF(String  designid,HttpServletRequest request,HttpServletResponse response) {
		// TODO Auto-generated method stub
 
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String template_path = basePath+"front/carDesign/craftOrderpdf?export=true&designid="+designid;
        // classpath 路径
    	String outputFileClass = ResourceLoader.getPath("");
    	
    	long timp=System.currentTimeMillis();
	    String    outputFile = new File(outputFileClass).getParentFile().getParent()+"/resources/download/"+timp+".pdf";
       
	    HttpHeaders headers = new HttpHeaders();    
	    File file;
	    ResponseEntity<byte[]> result = null;
		try {
			PdfDocumentGenerator.generate(HtmlUtil.findHtmlStringByURL(template_path), outputFile);
//	        System.out.println("-----------generate ok------------");
//	        new DownloadManager("d://partList.pdf",1,basePath+"resources/pdf/"+timp+".pdf").action();
//	        System.out.println("-----------download ok------------");
			
			//设置响应头，控制浏览器下载该文件
	        file = new File(outputFile);  
	        String fileName=new String("carInstruction.pdf".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
	        headers.setContentDispositionFormData("attachment", fileName);   
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   

	        result=  new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
	                headers, HttpStatus.CREATED);
	        
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
 
		}
        return result;  
	 
	}
 

}
